<template>
  <div class="live_info_view" v-loading="isLoading">


      <div style="padding-top:2%;height: 100px; width:850px;">
        <el-steps  :active="stepIndex" finish-status="success">
            <el-step title="step 1" description="创建直播间"></el-step>
            <el-step title="step 2" description="配置直播的基本信息,选择要直播的课程和班级后，点击开始直播"></el-step>
            <el-step title="step 3" description="开始推流"></el-step>
        </el-steps>
      </div>

      <div class="live-create-div" v-if="!haveLive">
        <div class="live-div" @click="createLive">
          <div style="position:absolute;">
            创建直播间 <i class="el-icon-s-promotion"></i>
          </div>
          <img :src="liveImg" alt="">
        </div>
      </div>


      <div v-if="haveLive && !liveStart" class="live_info">
          <div>
            <el-tag effect='plain'>Tips:  开启直播后，请使用OBS推流！！！</el-tag>
          </div>

          <div class="live_basic_info" style="width:600px;">
            <div style="height:50px;">
              基本信息：

            </div>
            <el-form ref="live" :model="live" label-width="100px" label-position="left">
              <el-form-item label="推流地址: ">
                <el-input v-model="live.livePushUrl" placeholder="请输入内容" disabled></el-input> 
                <span style="display: inline-block;">OBS推流地址,开始直播后，请将此地址复制到 OBS推流地址中</span>
              </el-form-item>
              <el-form-item label="密钥: " class="live_basic_info_item ">
                <el-input v-model="live.liveSecret" placeholder="请输入内容" disabled></el-input> 
                <span style="display: inline-block;">OBS推流密钥，请将此密钥复制到 OBS串流密钥上</span>
              </el-form-item>
              
              <el-form-item label="直播名称: " class="live_basic_info_item ">
                <el-input v-model="live.liveName" placeholder="请输入内容"></el-input>
              </el-form-item>

              
            </el-form>
          </div>
          <el-divider></el-divider>

          <div class="live_basic_info">
            <div style="height:50px;">
              直播配置：

            </div>
            <el-form ref="live" :model="live" label-width="100px" label-position="left">
            <!-- <el-form-item label="默认签到时长: ">
                <el-input-number v-model="live.signTimeLimit" :min="60" label="描述文字"></el-input-number>
                -- 建议时间稍长一些
            </el-form-item> -->
            <el-form-item label="直播课程: ">
                <el-select v-model="live.courseId" placeholder="选定课程">
                  <el-option :label="courseInfo.courseName" :value="courseInfo.courseId" v-for="courseInfo in myCourseInfo" :key="courseInfo.courseId">
                  </el-option>
                </el-select>
                
              </el-form-item>

              <el-form-item label="选定班级: " class="myclass-transfer">

                <el-transfer v-model="live.classIds" :titles="['可选班级', '已选班级']"
                :data="myClassInfo"></el-transfer>
                
              </el-form-item>

              <el-form-item label="是否允许其他班级加入:" label-width="160px">
                <el-switch
                  v-model="live.accessOtherClass"
                  active-text="允许"
                  :active-value="100"
                  inactive-text="不允许"
                  :inactive-value="0" >
                </el-switch>
                
                
              </el-form-item>
              <!-- <el-form-item> -->
                <el-tag type="danger">
                  Tips：使用推流工具推流后才会显示直播状态和互动功能！！！！
                </el-tag>
              <!-- </el-form-item> -->
              
            </el-form>
            
          <el-divider></el-divider>


          </div>

          <div class="start_live_div">

            <div class="live-div" @click="startLive">
                <div style="position:absolute;">
                  开始直播 <i class="el-icon-s-promotion"></i>
                </div>
                <img :src="liveImg" alt="">
            </div>

          </div>

      </div>
        

      <div v-if="liveStart" class="live-started-div">
        <div class="live-start-before-push">

            <div>
              <el-tag>当前直播已开启, 请使用 OBS 推流！</el-tag>
            </div>

            <div>
              <el-tooltip class="item" effect="dark" content="关闭直播" placement="left">
              <el-button @click="closeLive" type="danger" size="small" icon="el-icon-close" circle></el-button>
              </el-tooltip>
            </div>
        </div>
        
        

        <!-- isPush -->
        <div v-show="isPush">
          <div class="tag-item">
            <el-tag>接收到推流, 接下来您可以发起签到 和 发布选择题。</el-tag>
          </div>

          <el-tag class="tag-item" type="danger">
            请注意，签到因为直播延迟的原因也会在2-3s后才进行发布。
          </el-tag>

            <el-form ref="live" :model="signInfo" label-width="100px" label-position="left" style="margin-top:20px;">
                <el-form-item label="默认签到时长: ">
                    <el-input-number v-model="signInfo.signTimeLimit" :min="60" label="描述文字"></el-input-number>
                    -- 建议时间稍长一些。发起签到：
                    <el-button type="primary" icon="el-icon-s-promotion" 
                    @click="publishSign"
                    circle></el-button>
                </el-form-item>
            </el-form>

            <el-divider></el-divider>

            <el-form ref="form" :model="problemInfo" label-width="100px">
              <!-- <el-form-item label="问题类型: ">
                <el-tag type="info">文本题不计入分数。</el-tag> <br>
                 <el-radio v-model="problemInfo.type" :label="2">选择题</el-radio>
                 <el-radio v-model="problemInfo.type" :label="1">文本题</el-radio>

              </el-form-item> -->

              <!-- <el-form-item label="问题分数: " class="live-problem-item" v-if="problemInfo.type == 2">
                <el-input v-model="problemInfo.score"></el-input>
                <el-tag type="info">暂时只支持单项选择题</el-tag>
              </el-form-item> -->

              <el-form-item label="问题描述: ">
                <editor @editorContent="getContent"></editor>
              </el-form-item>


              <el-form-item label="设置选项:">
                    <el-button style="margin-top:1%;" @click="addCheck">+ 添加选项</el-button>
                    <el-tag style="margin-left:10px;" type="info">最多支持6个, 如果不够，请联系系统服务者进行添加</el-tag>
                    
                    
                    <div class="work-check-item" id="checkinfo">
                            <div  v-for="checkinfo,index in problemInfo.checkInfos" 
                            :key="index" style="margin-top:1%;">

                                {{checkinfo.label}} : 
                                <el-input class="check-input" v-model="checkinfo.content"></el-input>
                                <!-- <el-radio style="margin-left:2%;" border 
                                @change="changeTheTrueCheck(checkinfo.label)"
                                v-model="problemInfo.trueCheck" :label='checkinfo.label'>设为正确答案</el-radio> -->

                              
                            </div>
                    </div>

              </el-form-item>

              <el-form-item>
                <el-button type="primary" :loading="putProblemLoading" @click="publishProblem">发布问题</el-button>
              </el-form-item>
              
            </el-form>

            <el-divider></el-divider>

             <div class="live-right-chatinfo-div">
                    <div class="live-chatinfo">
                           <div v-for="chatinfo, index in chatInfos" :key="index" class="chat-item">
                              <el-image
                              class="chat-item-img"
                              style="width: 50px; height: 50px"
                              :src="chatinfo.stuAvatar"
                              fit="fill"></el-image>

                            <div class="chat-item-info">
                              {{chatinfo.stuName}}：{{chatinfo.info}}
                              
                            </div>
                            
                          </div>
                    </div>

        </div>

        </div>
      </div>
  </div>
</template>

<script>
import * as API from '../../api/live/index'
import {getMyCourse} from '../../api/course/index'
import {getAllClassInfo} from '../../api/class/index'
import Editor from '../../components/Editor.vue'
import {Storage} from '../../storage'
import Bus from '../../utils/bus'

export default {
  components: { Editor },
  data() {
    return {
      chatInfos:[],
      avater:require('../../../public/img/1.jpg'),
      isLoading:false,
      liveStart:false,
      haveLive:false,
      isPush:false,
      createShow:false,
      liveImg:require('../../../public/img/wave3.svg'),
      stepIndex: 0,
      live: {
        // url: "http:127.0.0.1:8080/api/live/XwyEhui",
        // name: "我的直播间",
        courseId: "",
        accessOtherClass: 0,
        classIds:[]
      },
      myCourseInfo:[],
      myClassInfo: [],
      signInfo:{
        signTimeLimit:180
      },
      problemInfo:{
        content:"",
        checkInfos:[{
          label:'A',
          content:'',
        }],
      },
      checkLabels:['A', 'B', 'C', 'D', 'E', 'F', 'G'],
      checkLabelIndex: 0,
      putProblemLoading:false,
      socket:'',
      teaId:'',
      lockReconnect: false,//是否真正建立连接
      timeout: 5 * 60 * 1000,//50分一次心跳
      timeoutObj: null,//心跳心跳倒计时
      serverTimeoutObj: null,//心跳倒计时
      timeoutnum: null,//断开 重连倒计时
    }
  },
  methods: {
    addChatItem(json) {
      this.chatInfos.push({
        stuName: json.data.stuName,
        stuAvatar: json.data.stuAvatar,
        info: json.data.info
      })
    },
    startLive() {
      console.log(this.live)
      API.startLive(this.live).then(res => {
        if(res.code == 200) {
          this.$notify({
            title: '成功',
            message: '开播成功，注意：使用推流工具推流后才会显示直播状态和互动功能！！！！',
            type: 'success'
          });
          this.stepIndex = 2
          this.liveStart = true
        }else {
          this.$notify.error({
            title: '警告',
            message: '开播失败，' + res.data.error,
          });
        }
      })
    },
    createLive() {
      API.createMyLiveRoom().then(res => {
        if(res.code == 200) {
          
          this.$message({
            message: '创建成功',
            type: 'success'
          });
          this.haveLive = true
          
          this.stepIndex = 1
          
          this.live = res.data.liveInfo
        }else {
          this.$message({
            message: res.data.error,
            type: 'error'
          });
          this.haveLive = true
          this.stepIndex = 1
          this.getMyLiveRoomInfo()
        }

        getMyCourse().then(res => {
              if(res.code == 200) {
                res.data.courses.forEach(course => {
                  this.myCourseInfo.push({
                      courseId: course.courseId,
                      courseName: course.courseName
                    })
                })
              }
              
            })

        getAllClassInfo(1, 2).then(res => {
              if(res.code == 200) {
                res.data.classInfos.forEach(classInfo => {
                  this.myClassInfo.push({
                    key: classInfo.classId,
                    label: classInfo.classRealName
                  })
                });
              }
        })
      
      })
    },
    getInitInfo() {
      API.getLiveInitInfo().then(res => {
        if(res.code == 200) {
          this.haveLive = res.data.initInfo.liveHave          
          
          this.liveStart = res.data.initInfo.start

          if(this.haveLive) {
            this.stepIndex = 1 
            this.getMyLiveRoomInfo()
            if(res.data.initInfo.push == false) {
              this.getCourseAndClassInfo()

            }else {
              this.isPush = res.data.initInfo.push
            }

          }

          if(this.liveStart) {
            this.stepIndex = 2
          }

          if(this.isPush) {
            this.stepIndex = 3 
          }
          
        }else {
          this.$message.error(res.data.error);
        }
        this.isLoading = false
      }).catch(err => {
        this.$message.error("网络出错了");
      })
    },
    getCourseAndClassInfo() {
              getMyCourse().then(res => {
                if(res.code == 200) {
                  res.data.courses.forEach(course => {
                    this.myCourseInfo.push({
                        courseId: course.courseId,
                        courseName: course.courseName
                      })
                  })
                }
                
              })
  
              getAllClassInfo(1, 2).then(res => {
                if(res.code == 200) {
                  res.data.classInfos.forEach(classInfo => {
                    this.myClassInfo.push({
                      key: classInfo.classId,
                      label: classInfo.classRealName
                    })
                  });
                }
              })
    },
    getMyLiveRoomInfo() {
      API.getMyLiveRoomInfo().then(res => {
        if(res.code == 200 && res.data.liveInfo != null) {
          this.live = res.data.liveInfo
        }else if(res.code == 100) {
          this.$message.error(res.data.error);
        }
      }).catch(err => {
        this.$message.error("网络出错了" + err);
      })
    },
    changeTheTrueCheck(label){
      console.log(label)
        this.problemInfo.checkInfos.forEach(checkInfo => {
            if(checkInfo.label === label) {
                checkInfo.isTrueCheck = true
            }else {
                     checkInfo.isTrueCheck = false
            }
        })
    },
    addCheck() {
      if(this.checkLabelIndex >= 5) return
      let newLabel = this.checkLabels[++this.checkLabelIndex]
      this.problemInfo.checkInfos.push({
          label: newLabel,
          content: "",
      })
    },
    getContent(content) {
      this.problemInfo.content = content
    },
    tolinkWebsocket(teaId) {
            if(typeof(WebSocket) === "undefined"){
                alert("您的浏览器不支持socket")
            }else{
                // 实例化socket
                this.socket = new WebSocket(`ws://127.0.0.1:8900/live_start/${teaId}`)
                // 监听socket连接
                this.socket.onopen = this.onopen
                // 监听socket错误信息
                this.socket.onerror = this.onerror
                // 监听socket消息
                this.socket.onmessage = this.ongetMessage
                this.socket.onclose = this.onclose
            }
    },
    onopen() {
        console.log("ws on open")
        //开启心跳
        this.start();
    },
    onerror() {
        console.log("ws on error")
    },
    ongetMessage(msg) {
        let data = JSON.parse(msg.data);
        //如果是心跳检测的话，那么不予例会
        if(data.code == 202) {
          this.reset();
          return;
        }  else if(data.code == 206) {
          this.addChatItem(data)
          return
        }

        this.isPush = data.data.push
        if(this.isPush) {
          this.stepIndex = 3 
        }else{
          this.stepIndex = 2
        }
        //收到服务器信息，心跳重置
        this.reset();
    },
    onclose() {
        // this.socket.close()
        console.log("socket已经关闭")
    },
    reset(){//重置心跳
        //清除时间
        clearTimeout(this.timeoutObj);
        clearTimeout(this.serverTimeoutObj);
        //重启心跳
        this.start();
    },
    start(){//开启心跳
        this.timeoutObj && clearTimeout(this.timeoutObj);
        this.serverTimeoutObj && clearTimeout(this.serverTimeoutObj);
        this.timeoutObj = setTimeout(() => {
          console.log(this.socket)
          //这里发送一个心跳，后端收到后，返回一个心跳消息，
          if (this.socket.readyState == 1) {//如果连接正常
            let r = {code:202, msg:"ping"} 
            
            this.socket.send(JSON.stringify(r));
          }

          // this.serverTimeoutObj = setTimeout(function() {
          //     if(this.socket != '') {
          //       //超时关闭
          //       this.socket.close();
          //     }
          //     //超时后3秒关闭
          // }, 5 * 1000);
 
        }, this.timeout)
    },
    closeLive() {
      API.closeLive(this.live.liveUuid).then(res => {
        if(res.code == 200) {
          
          this.$message({
            message: '关闭成功',
            type: 'success'
          });
          this.liveStart = false
          this.stepIndex = 1
        }else {
          this.$message({
            message: res.data.error,
            type: 'error'
          });
        }
      })
    },
    publishSign() {
      API.publishSign(this.live.liveUuid, this.signInfo).then(res => {
        if(res.code == 200) {
          this.$message({
            message: '发布签到成功，会有2-3s的延迟。',
            type: 'success'
          });
        }else {
          this.$message.error(res.data.error);
        }
      }).catch(err => {
        this.$message.error("网络不太好， err:" + err);
      })
    },
    publishProblem() {
      this.putProblemLoading = true
      API.publishProblem(this.live.liveUuid, this.problemInfo).then(res => {
        if(res.code == 200) {
          this.$message({
            message: '发布问题成功，会有2-3s的延迟。',
            type: 'success'
          });
        }else {
          this.$message.error(res.data.error);
        }
        this.putProblemLoading = false
      }).catch(err => {
        this.$message.error("网络不太好， err:" + err);
        this.putProblemLoading = false
      })

    }
  },
  watch: {
  },
  mounted() {
    this.isLoading = true
    let tea =  Storage.get("tea")
    if(tea != undefined && tea != '') {
      this.teaId = Storage.get("tea").teaId
      this.tolinkWebsocket(this.teaId)
      this.getInitInfo()
    }else {
      Bus.$on("isLogin",(val) => {
        this.teaId = Storage.get("tea").teaId
        this.tolinkWebsocket(this.teaId)
        this.getInitInfo()
      })
    }

    
    
  },
  destroyed() {
    this.socket.close()
  }
}
</script>

<style>
.live_info_view {
    width: 100%;
    display: flex;
    flex-direction: column;
    justify-content: center;
    align-items: center;
}

.live-create-div {
  width: 96%;
  display: flex;
  align-items: center;
  justify-content: center;
}

.live-div {
  padding-left: -3px;
  margin-top: 10%;
  width: 150px;
  height: 150px;
  padding: 0%;
  display: flex;
  align-items: center;
  justify-content: center;
  border-radius: 50%;
  /* background:#2499ff; */
  overflow: hidden;
  /* box-shadow: 0 2px 12px   0px rgb(255 215  0 / 8%); */
  border: 1px dashed rgb(255, 215, 0);
  cursor: pointer;
}

.live-div > img {
  /* width: 600px; */
  margin-top: -45px;
  height: 230px;
  transition: all 7s;
  margin-left: 650px;
}

.live-div:hover > img {
  margin-left: -500px;
}

.live_info {
  margin-top: 2%;
  display: flex;
  flex-direction: column;
  align-items: flex-start;

}

.live_basic_info {
  width: 800px;
  margin-top: 2%;
}

.live_basic_info_item {
  width: 450px;
}

.start_live_div {
  margin-top: -55px;
  width: 800px;
  display: flex;
  justify-content: center;
}

.myclass-transfer > .el-form-item__content > .el-transfer > .el-transfer-panel {
  width: 258px;
}

.live-started-div {
  width: 750px;
  min-height: 300px;
  background: white;
  box-shadow: 0 2px 12px 0px rgb(0 0 0 / 15%);
  padding: 2%;
}

.live-problem-item {
  width: 300px;
}

.tag-item {
  margin-top: 10px;
}

.live-start-before-push {
  display: flex;
  justify-content: space-between;
}

.live-right-chatinfo-div {
  /* width:100%; */
  height: 600px;
  overflow-y:scroll;
}

.live-chatinfo {
  margin-top: -2%;
  display: flex;
  flex-direction: column;
}

.chat-item {
  /* width: 100%; */
  padding-left: 2%;
  margin: 2% 2% 0% 2%;
  /* min-height: 100px; */
  font-size: 15px;
  display: flex;
  align-items: center;
  border-radius: 10px;

}

.chat-item-img {
  min-width: 50px; 
  max-height: 50px;
  border-radius: 50%;
  overflow: hidden;
  display: flex;
  align-items: center;
}

.chat-item-info {
  margin-left: 2%;
  display: flex;
  align-items: center;
  
}
</style>